/** @file    FormFileSystem.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormFileSystem.cpp 2867 2010-08-07 20:44:51Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormFileSystem class.
 * The header for this class can be found in FormFileSystem.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "FormFileSystem.h"
 #include "ui_FormFileSystem.h"
 #include <core/FileSystem.h>
 #include <core/List.h>

 #include <QtGui/QInputDialog>


using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormFileSystem, "wosh::gui::IWidgetGeneric", 1.0, _static_FormFileSystem )
 WOSH_GUI_MAP(wosh::gui::FormFileSystem, "wosh::FileSystem", 0.0, _static_Map_FormFileSystem )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FileInfoTreeModel::FileInfoTreeModel( Tree* tree_data, QObject *parent )
	: WoshTreeModel(tree_data, parent) { }
 
QVariant FileInfoTreeModel::data( const QModelIndex &index, int role ) const {
	if ( !index.isValid() )	return QVariant();
	TreeNode* item = static_cast<TreeNode*>(index.internalPointer());
	if ( item == NULL || item->getContent() == NULL ) return QVariant();
	const FileInfo* info = dynamic_cast<const FileInfo*>(item->getContent());
	if ( info == NULL ) return QVariant("NULL");
	if ( role == Qt::DisplayRole ) {
		switch (index.column()) {
			case 0:		return QVariant( info->local_path.c_str() );
			case 1:		return QVariant( QDateTime().fromTime_t(info->time_created) );
			case 2:		return QVariant( info->size );
			default:	return QVariant();
		 }
	 }
	else if ( role == Qt::BackgroundColorRole ) {
		string local_path;
		FilePath fpath(info->wosh_path);
		if ( fpath.exists() )
			return QColor(229,255,229);
		return QColor(255,198,179);
	 }
	else if ( index.column() == 0 && role == Qt::DecorationRole ) {}
	return QVariant();
 }

QVariant FileInfoTreeModel::headerData( int section, Qt::Orientation orientation, int role ) const {
	if (role != Qt::DisplayRole) return QVariant();
	if (orientation == Qt::Horizontal) {
		 switch(section) {
			case 0:		return QString("Path");
			case 1:		return QString("Creation Time");
			case 2:		return QString("Size");
		  }
		 return QString("Col%1").arg(section);
	 }
	return QVariant();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FormFileSystem::FormFileSystem(QWidget *parent)
	: IWidgetGeneric(parent) {
	this->m_ui = new Ui::FormFileSystem();
	this->m_ui->setupUi(this);

	IWidgetGeneric::setTargetURI(_FileSystem_URI);
	buildMenus();

	// tab FileSystem [0]
	this->treeModel = new FileInfoTreeModel( NULL, this);
	this->m_ui->treeViewFileSystem->setModel(this->treeModel);
	connect(this->m_ui->treeViewFileSystem, SIGNAL(clicked(const QModelIndex&)), this, SLOT(treeViewFileSystem_clicked(const QModelIndex&)));
	connect(this->m_ui->treeViewFileSystem, SIGNAL(doubleClicked(const QModelIndex&)), this, SLOT(treeViewFileSystem_doubleClicked(const QModelIndex&)));
	connect(this->m_ui->wUpBarFileSystem, SIGNAL(updateClicked()), this, SLOT(refreshFileSystem()));
	connect(this->treeModel, SIGNAL(s_requestChildrenOf(const QModelIndex&)), this, SLOT(treeModel_requestChildrenOf(const QModelIndex&)));
	this->treeModel->setFetchMore( true );

	// tab Aliases [1]
	this->m_ui->tableViewAliases->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewAliases, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewAliases, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableViewAliases_ContextMenu(const QPoint&, const QModelIndex&)) );
	connect(this->m_ui->btnAddAlias, SIGNAL(clicked()), this, SLOT(btnAddAlias_clicked()));
	connect(this->m_ui->btnRemoveAlias, SIGNAL(clicked()), this, SLOT(btnRemoveAlias_clicked()));
 }

FormFileSystem::~FormFileSystem() {
	delete this->m_ui;
 }

void FormFileSystem::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormFileSystem::refreshAll() {
	this->setWindowTitle( QString("FileSystem [%1]").arg(this->getTargetURI().getKernelName().c_str()) );
	refreshFileSystem();
	this->m_ui->tableViewAliases->refreshData();
 }
void FormFileSystem::refreshFileSystem() {
	executeRemoteMethod( _FileSystem_METHOD_dir_tree, new Variant("$ROOT") );
	this->m_ui->wUpBarFileSystem->sayRetrieving();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormFileSystem::treeViewFileSystem_clicked( const QModelIndex& index ) {
	//TreeNode* item = static_cast<TreeNode*>(index.internalPointer());
	//if ( item == NULL || item->getContent() == NULL ) return;
	//const FileInfo* fileitem = dynamic_cast<const FileInfo*>(item->getContent());
	//if ( fileitem == NULL ) return;
	//executeRemoteMethod( _FileSystem_METHOD_dir_tree, new Variant(fileitem->local_path) );
	//this->m_ui->wUpBarFileSystem->sayRetrieving();
 }

void FormFileSystem::treeViewFileSystem_doubleClicked( const QModelIndex& ) {

 }

void FormFileSystem::treeModel_requestChildrenOf( const QModelIndex& index ) {
	TreeNode* item = static_cast<TreeNode*>(index.internalPointer());
	if ( item == NULL || item->getContent() == NULL ) return;
	const FileInfo* fileitem = dynamic_cast<const FileInfo*>(item->getContent());
	if ( fileitem == NULL ) return;
	executeRemoteMethod( _FileSystem_METHOD_dir_tree, new Variant(fileitem->local_path) );
	this->m_ui->wUpBarFileSystem->sayRetrieving();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormFileSystem::buildMenus() {
	this->menuAliasTitle = new QAction(this);
	this->menuAliasTitle->setEnabled(false);
	this->menuAliasRemove = new QAction(this);
	this->menuAliasRemove->setText(tr("&Remove"));
	this->menuAliasEdit = new QAction(this);
	this->menuAliasEdit->setText(tr("&Edit.."));
	this->menuAlias = new QMenu(this);
	this->menuAlias->addAction(this->menuAliasTitle);
	this->menuAlias->addSeparator();
	this->menuAlias->addAction(this->menuAliasRemove);
	this->menuAlias->addAction(this->menuAliasEdit);
 }

void FormFileSystem::tableViewAliases_ContextMenu( const QPoint& pos, const QModelIndex& index ) {
	QPoint globalPos = this->mapToGlobal(pos);
	if ( !index.isValid() || index.row() == 0 ) return;
	Variant aliasName = this->m_ui->tableViewAliases->getCurrentItemAsVariantAtCol(0);
	this->menuAliasTitle->setText( aliasName.toString().c_str() );
	QAction* selected = this->menuAlias->exec( globalPos );
	if ( selected == this->menuAliasRemove ) {
		executeRemoteMethod( _FileSystem_METHOD_rem_alias, aliasName.clone() );
 	 }
	else if ( selected == this->menuAliasEdit ) {
		Variant aliasOldValue = this->m_ui->tableViewAliases->getCurrentItemAsVariantAtCol(1);
		bool ok;
		QString aliasValue = QInputDialog::getText(this, tr("Edit Alias '%1'..").arg(aliasName.toString().c_str()), tr("Local Path (such as 'C:\\WOSH', or '$ROOT/var'):"), QLineEdit::Normal, aliasOldValue.toString().c_str(), &ok);
		if ( !ok || aliasValue.isEmpty() ) return;
		List* vals = new List(2);
		vals->push_back<Variant>( aliasName );
		vals->push_back<Variant>( aliasValue.toStdString() );
		executeRemoteMethod( _FileSystem_METHOD_set_alias, vals );
	 }
 }

void FormFileSystem::btnRemoveAlias_clicked() {
	Variant aliasName = this->m_ui->tableViewAliases->getCurrentItemAsVariantAtCol(0);
	executeRemoteMethod( _FileSystem_METHOD_rem_alias, aliasName.clone() );
 }

void FormFileSystem::btnAddAlias_clicked() {
	bool ok;
	QString aliasName = QInputDialog::getText(this, tr("Add Alias.."), tr("Name (such as 'ROOT'):"), QLineEdit::Normal, "", &ok);
	if ( !ok || aliasName.isEmpty() ) return;
	QString aliasValue = QInputDialog::getText(this, tr("Add Alias.."), tr("Local Path (such as 'C:\\WOSH', or '$ROOT/var'):"), QLineEdit::Normal, "", &ok);
	if ( !ok || aliasValue.isEmpty() ) return;
	List* vals = new List(2);
	vals->push_back<Variant>( aliasName.toStdString() );
	vals->push_back<Variant>( aliasValue.toStdString() );
	executeRemoteMethod( _FileSystem_METHOD_set_alias, vals );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormFileSystem::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() || !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	this->m_ui->tableViewAliases->evalResponse(response);

	if ( response->getMethod() == _FileSystem_METHOD_set_alias || response->getMethod() == _FileSystem_METHOD_rem_alias )
		this->m_ui->tableViewAliases->refreshData();

	promptMethodResponse(message);

	if ( response->getMethod() == _FileSystem_METHOD_set_alias ) {
		this->m_ui->tableViewAliases->getUpdateBar()->showMessage( tr("Applied Alias!") );
		return;
	 }
	else if ( response->getMethod() == _FileSystem_METHOD_rem_alias ) {
		this->m_ui->tableViewAliases->getUpdateBar()->showMessage( tr("Removed Alias!") );
		return;
	 }

	else if ( response->getMethod() == _FileSystem_METHOD_dir_tree ) {
		if ( !response->hasData() ) return;
		if ( !response->getData()->isKindOf<Tree>() ) return;
		this->treeModel->loadTree( response->getData()->as<Tree>() );
		this->m_ui->treeViewFileSystem->header()->setResizeMode(0, QHeaderView::Stretch);
		this->m_ui->treeViewFileSystem->resizeColumnToContents(0);
		this->m_ui->wUpBarFileSystem->sayReady();
		return;
	 }
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
